import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../../providers/order_provider.dart';
import '../../../utils/g.dart';

class UserCoupon extends StatefulWidget {
  const UserCoupon({Key? key}) : super(key: key);

  @override
  _UserCouponState createState() => _UserCouponState();
}

class _UserCouponState extends State<UserCoupon> {
  Map coupon = {};

  @override
  Widget build(BuildContext context) {
    coupon = Provider.of<OrderProvider>(context).coupon;

    return Container(
      margin: const EdgeInsets.all(10),
      padding: const EdgeInsets.all(10),
      height: 50,
      decoration: BoxDecoration(
        border: Border.all(width: 1, color: Colors.grey.shade300)
      ),
      child: InkWell(
        onTap: () {
          // 触发优惠券弹窗
          _getCouponDialog(context);
        },
        child: Flex(
          direction: Axis.horizontal,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Text('优惠券'),
            Row(
              children: [
                Text(
                  coupon['coupon_title'] ?? '请选择',
                  style: const TextStyle(color: Colors.grey)
                ),
                const Icon(
                  Icons.chevron_right,
                  size: 24,
                  color: Colors.grey
                )
              ],
            )
          ],
        )
      ),
    );
  }

  void _getCouponDialog(context) {
    showModalBottomSheet(
      context: context, 
      shape: const RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20),
          topRight: Radius.circular(20),
        )
      ),
      builder: (BuildContext context) {
        return StatefulBuilder(
          builder: (BuildContext ctx, StateSetter stateSetter) {
            return Column(
              children: [
                _renderCouponList(context, stateSetter),
              ],
            );
          }
        );
      }
    );
  }

  Widget _renderCouponList(BuildContext context, StateSetter stateSetter) {
    List couponList = [];

    return FutureBuilder(
      future: G.api.coupon.list(),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          var res = snapshot.data as Map;
          if (res['status'] == 200) {
            couponList = res['data'];

            return Container(
              margin: const EdgeInsets.fromLTRB(0, 0, 0, 30),
              child: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                physics: const BouncingScrollPhysics(),
                child: Column(
                  children: [
                    Container(
                      margin: const EdgeInsets.all(20),
                      child: const Center(
                        child: Text(
                          "优惠券",
                          style: TextStyle(
                            fontSize: 24,
                            fontWeight: FontWeight.w600
                          ),
                        )
                      ),
                    ),
                    Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: couponList.isNotEmpty
                      ?
                      couponList.map<Widget>((item) {
                        return ListTile(
                          onTap: () {
                            Provider.of<OrderProvider>(context, listen: false).setCoupon(item);
                            // 重新计算订单价格
                            Provider.of<OrderProvider>(context, listen: false).setOrderPrice();

                            Navigator.pop(context);
                          },
                          title: Text(item['coupon_title'].toString()),
                          subtitle: Row(
                            children: [
                              Text(item['add_time'].toString()),
                              Text(" - "+item['end_time'].toString()),
                            ],
                          ),
                          trailing: Text(
                            "￥ "+item['coupon_price'].toString(),
                            style: TextStyle(
                              color: Theme.of(context).primaryColor,
                              fontSize: 30,
                              fontWeight: FontWeight.w600
                            )
                          ),
                          selected: coupon['id'] == item['id'],
                          selectedTileColor: Colors.grey.shade100,
                        );
                      }).toList()
                      : [const Center(child: Text('空空如也~'))],
                    )
                  ],
                ),
              ),
            );
          } else {
            // 报错
            G.error('获取优惠券列表失败');
          }
        } else if (snapshot.hasError) {
          return Center(
            child: Text("${snapshot.error}"),
          );
        }

        return G.loader();
      }
    );
  }
}